<template>
  <template v-for="(tag, index) in tags" :key="index">
    <Tag closable @close="handleClose(tag)">
      {{ tag }}
    </Tag>
  </template>
  <a-input
    v-if="inputVisible"
    ref="inputRef"
    type="text"
    :style="{ width: '78px' }"
    v-model:value="inputValue"
    @blur="handleInputConfirm"
    @keyup.enter="handleInputConfirm"
  />
  <Tag v-else @click="showInput" style="background: #fff; border-style: dashed">
    <plus-outlined />
    New Tag
  </Tag>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, nextTick } from 'vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { Tag } from 'ant-design-vue';

  export default defineComponent({
    components: {
      PlusOutlined,
      Tag,
    },
    props: {
      taglist: {
        type: Array,
        default: [],
      },
    },
    emits: ['ok'],
    setup(props, { emit }) {
      const inputRef = ref();
      const state = reactive({
        tags: [],
        inputVisible: false,
        inputValue: '',
      });
      state.tags = props.taglist;
      const handleClose = (removedTag: string) => {
        const tags = state.tags.filter((tag) => tag !== removedTag);
        state.tags = tags;
        emit('ok', state.tags);
      };
      const showInput = () => {
        state.inputVisible = true;
        nextTick(() => {
          inputRef.value.focus();
        });
      };
      const handleInputConfirm = () => {
        const inputValue = state.inputValue;
        let tags = state.tags;
        if (inputValue && tags.indexOf(inputValue) === -1) {
          tags = [...tags, inputValue];
        }
        Object.assign(state, {
          tags,
          inputVisible: false,
          inputValue: '',
        });
        emit('ok', state.tags);
      };
      return {
        ...toRefs(state),
        handleClose,
        showInput,
        handleInputConfirm,
        inputRef,
      };
    },
  });
</script>
